package com.bb;

import io.jsonwebtoken.*;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;

@SpringBootTest
public class JwtTest {
    //创建Token
    @Test
    public void testBuildingToken() {
        //1.创建JwtBuilder对象
        JwtBuilder builder = Jwts.builder();
        //2.设置头部
        builder.setHeaderParam("alg", "HS256"); //设置签名算法
        builder.setHeaderParam("typ", "JWT"); //设置令牌类型

        //3.设置有效载荷(同时设置自定义字段)
        builder.setSubject("书城令牌");  //设置主题
        builder.setIssuer("云上城主");    //设置签发者

        //设置过期时间为30分钟，单位是毫秒
        long EXPIRATION = 30 * 60 * 1000;
        builder.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION));

        builder.claim("userId", "1001"); //设置自定义字段
        builder.claim("name", "user");
        builder.claim("password", "1314ggg");
        //4.设置签证
        String SECRET = "dog520";
        builder.signWith(SignatureAlgorithm.HS256, SECRET); //设置签名算法和签名密钥
        //5.生成Token
        String token = builder.compact();
        System.out.println("生成的Token为："+ token);

    }

    //解析Token
    @Test
    public void testParsingToken() {
        //得到token
        String token ="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiLkuabln47ku6TniYwiLCJpc3MiOiLkupHkuIrln47kuLsiLCJleHAiOjE3NDcyMTQ1NjgsInVzZXJJZCI6IjEwMDEiLCJuYW1lIjoidXNlciIsInBhc3N3b3JkIjoiMTMxNGdnZyJ9.MX6FoarRlKEgimG7zJJ9fV3wFJAZ_nD6iMaQ3Vo9UD4";
        //1.创建JwtParser对象
        JwtParser parser = Jwts.parser();
        //2.设置签名的秘钥
        parser.setSigningKey("dog520");
        //3.解析Token
        Jws<Claims> claimsJws = parser.parseClaimsJws(token);
        //4.得到载荷
        Claims claims = claimsJws.getBody();
        //5.从载荷中获取数据
        System.out.println(claims);
        System.out.println("userId：" + claims.get("userId"));
        System.out.println("name：" + claims.get("name"));
        System.out.println("password：" + claims.get("password"));
    }
}
